<?php
/**
* Template management.
*
* Copyright (c) 2009 James Gauld <james@jamesgauld.net>
* This file is part of Scribble.
* @license http://www.scribblecms.co.uk/license.txt
*
* @package Scribble
*/
use Buan\Config;
use Buan\Inflector;
class ScribbleTemplateManager {

	/**
	* Template paths.
	*
	* @var array
	*/
	static private $templatePaths = array();

	/**
	* Add a source of templates. The folder you specify here must contain a list
	* of template folders.
	*
	* @param string Absolute folder path
	* @param string Absolute URL path
	* @return void
	*/
	static public function addTemplatePath($folder, $url) {
		$p = new StdClass();
		$p->folder = $folder;
		$p->url = $url;
		self::$templatePaths[] = $p;
	}

	/**
	* Returns the name of the default outer template which is used when a
	* requested URL doesn't result in a matching Page.
	*
	* @return string
	*/
	static public function getDefaultOuterTemplate() {
		return Config::get('ext.Scribble.defaultTemplate');
	}

	/**
	* Find the template matching the given name.
	*
	* @param string $name
	* @return ScribbleTemplate
	* @throws ScribbleTemplateException
	*/
	static public function getTemplateByName($name) {
		$className = "ScribbleTemplate_".Inflector::lowerHyphenated_lowerCamelCaps($name);
		foreach(self::$templatePaths as $tp) {
			$classPath = "{$tp->folder}/{$name}/{$className}.php";
			if(file_exists($classPath)) {
				include_once($classPath);
				$tpl = new $className($name);
				$tpl->setBaseFolder($tp->folder);
				$tpl->setBaseUrl($tp->url);
				return $tpl;
			}
		}
		throw new ScribbleTemplateException("Unknown template, {$name}");
	}

	/**
	* Return a list of ScribbleTemplate objects that are available on the system.
	* If you specify a template type then only templates of that type will be
	* returned, otherwise ALL templates are returned.
	*
	* @param int Template type to return
	* @return array
	*/
	static public function getTemplateChoices($type=NULL) {
		$templates = array();
		foreach(self::$templatePaths as $tp) {
			$dh = new DirectoryIterator($tp->folder);
			foreach($dh as $f) {
				if($f->isDir() && !$f->isDot() && !preg_match("/^\./", $f->getFilename())) {
					$tpl = self::getTemplateByName($f->getFilename());
					if($type===NULL || $tpl->getType()===$type) {
						$templates[$f->getFilename()] = $tpl;
					}
				}
			}
		}
		ksort($templates);
		return array_values($templates);
	}

	/**
	* Returns the template paths currently available.
	*
	* @return array
	*/
	static public function getTemplatePaths() {
		return self::$templatePaths;
	}

	/**
	* Sets the outer template that will be used by default in cases of missing
	* page requests.
	*
	* @param string Template name
	* @return void
	*/
	static public function setDefaultOuterTemplate($name) {
		Config::set('ext.Scribble.defaultTemplate', $name);
	}
}
?>